package gx.dao.impl.common;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Repository;

import gx.dao.PurchaseDao;
import gx.dao.impl.common.BaseDaoImpl;
import gx.entity.Purchase;
import gx.entity.common.Page;



@Repository
@SuppressWarnings("all") //去掉所以警告
public class PurchaseDaoImpl extends BaseDaoImpl<Purchase> implements PurchaseDao {

	@Override
	
	public Page<Purchase> findByStatus(int size, int number, Integer... status) {

		StringBuffer hql = new StringBuffer(
				"select  count(p)  from Purchase  p  where  1=1");
		StringBuffer hql2 = new StringBuffer("from Purchase p where 1=1");

		int length = status == null ? 0 : status.length;
		if (length > 0) {
			hql.append("and  p.status  in (");
			hql2.append("and p.status  in (");
		}

		for (int i = 0; i < length; i++) {
			if (i > 0) {
				hql.append(",");
				hql2.append(",");
			}
			hql.append(status[i]);
			hql2.append(status[i]);
		}
		if (length > 0) {
			hql.append(")");
			hql2.append(")");
		}
		hql2.append(" order  by   p.id  desc");
		// 总条数
		long count = total(hql.toString());
		Page<Purchase> page = new Page<Purchase>();
		page.setNumber(number); // 页数
		page.setSize(size); // 显示条数
		if (count > 0) {
			page.setTotalElements(count); // 总条数
			// 查找所有信息
			List<Purchase> list = getSession().createQuery(hql2.toString())
					.setMaxResults(size).setFirstResult((number - 1) * size)
					.list();
			page.setContent(list); // 当前页的数据集合
		}
		return page;
	
	}
	
	
    //动态查询 使用Hibernate的DetacherdCriteria
	@Override
	public Page<Purchase> findByCriteria(int size, int number, DetachedCriteria dc, DetachedCriteria dc2,DetachedCriteria dc3) {
		// TODO Auto-generated method stub
		Page<Purchase> pg = new Page<Purchase>();
		pg.setNumber(number);//页数
		pg.setSize(size);//条数
		
		
		//查询总记录数
		//"select count(*) from Purchase where status=? and pur_date>? and pur_date<?"
		Long temp = (Long)dc2.getExecutableCriteria(getSession()).uniqueResult();
		
		if(temp != null && temp.longValue() > 0){
			pg.setTotalElements(temp.longValue()); //总条数
			
			List<Purchase> list = dc.getExecutableCriteria(getSession())
					.setMaxResults(size)
					.setFirstResult((number - 1) * size)
					.list();
			pg.setContent(list);//当前页面中的所有数据集合
		}
		
		return pg;
	}




}
